<script type="text/ecmascript-6">
    /**
     * Created by wcz on 2017/1/5.
     */
    import imgView from '../base/imgView.vue'

    export default {
        data () {
            return {
                searchForm: {
                    de_name: '',
                    de_id: '',
                    c_id: '',
                    c_num: '',
                    state: '3',
                    upstream: ''
                },
                tasks: [],
                statusMap: {
                    0: '待审查',
                    1: '审核通过',
                    2: '审查未通过',
                    3: '车辆查找中',
                    4: '车辆已发现',
                    5: '任务完成',
                    6: '任务关闭',
                    7: '车辆已委托清收',
                    8: '车辆已锁定'
                },
                statusClass: {
                    0: 'b16',
                    1: 'b16',
                    2: 'b16',
                    3: 'b14',
                    4: 'b11',
                    5: 'b11',
                    6: 'b19',
                    7: 'b8',
                    8: 'b2',
                },
                pointIdx: 0,
                pageIndex: 1,
                pageSize: 100,
                storeComments: [],
                commentLoading: false,
                commentMap: {
                    "0": '库存',
                    "1": '正常',
                    "2": '正常',
                    "3": '正常',
                },
                entrustMap: {
                    "0": '全',
                    "1": '找',
                    "2": '清'
                },
                entrustFeeMap: {
                    "0": '处置',
                    "1": '查找',
                    "2": '清收'
                },
                upstreams: [],
                geocoder: null,
                tasksCount4: 0,
                tasksCount7: 0,
                tasksCount8: 0,
                sortWay: true, // true 为默认时间, false为残值排序
            }
        },
        created () {
            AMap.service('AMap.Geocoder', () => {
                //实例化Geocoder
                this.geocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                });
            })
        },
        computed: {
            pointTask () {
                return this.tasks[this.pointIdx]
            },
            hasTask () {
                return this.tasks.length > 0
            },
            isCommentsEmpty () {
                return this.storeComments.length == 0
            },
            taskActionTxt () {
                // 置为完成状态
                return '清收完成'
            },
            taskNextState () {
                // 置为完成状态
                return 5
            },
            downloadHref () {
                return `${host}/export/task?state=${this.searchForm.state}&s=999999`
            }
        },
        mounted () {
            this.getList();
            this.getUpStrem();
            this.getCount();
            setInterval(() => {
                this.getCount();
            }, 5000)
        },
        methods: {
            getList (currentPage = 1) {
                this.sortWay      = true;
                let postData      = {};
                postData.p        = currentPage;
                postData.s        = this.pageSize;
                postData.c_num    = this.searchForm.c_num;
                postData.state    = this.searchForm.state;
                postData.c_brand  = this.searchForm.c_brand;
                postData.c_series = this.searchForm.c_series;
                postData.upstream = this.searchForm.upstream;

                this.get('/api/v1/tasks', postData, {loading: 'xhrPending', err: '获取任务列表失败'})
                    .then(res => {
                        if (res.success && res.data.rows) {
                            this.tasks = res.data.rows.map(e => {
                                let ele      = e;
                                ele.bg       = `b${~~(Math.random() * 19 + 1)}`;
                                ele.stBg     = this.statusClass[e.state];
                                ele.stMsg    = this.statusMap[e.state];
                                ele.time     = e.create_at.split(' ')[0];
                                ele.extText  = `[${e.premium ? '加' : ''}${this.entrustMap[e.entrust]}]`;
                                ele.car_type = `${e.car_brand} - ${e.car_series} - ${e.car_model}`;
                                ele.C        = this.expected(e.entrust, Number(e.car_price));
                                return ele
                            });
                            if (this.tasks.length) {
                                this.getComments(this.tasks[0].id);
                            }
                        }

                    })
            },
            expected (entrust ,N = 0) {
                let C = 0;
                let x = 2;
                let y = N;
                let z = 0;

                if (N > 6 && N <= 10) {
                    y = 6;
                    z = 0.125;
                } else if (N > 10 && N <= 15) {
                    x = 2.5;
                    y = 10;
                    z = 0.2;
                } else if (N > 15 && N <= 20) {
                    x = 3.5;
                    y = 15;
                    z = 0.1;
                } else if (N > 20 && N <= 30) {
                    x = 4;
                    y = 20;
                    z = 0.2;
                } else if (N > 30 && N <= 60) {
                    x = 6;
                    y = 30;
                    z = 0.1;
                } else if (N > 60 && N <= 80) {
                    x = 9;
                    y = 60;
                    z = 0.15;
                } else if (N > 80) {
                    x = 0;
                    y = 0;
                    z = 0.15;
                }

                const serviceFeeCoefficient = {
                    0: 1,
                    1: 0.3,
                    2: 0.8
                };

                C = N ? x + (N - y) * z : 0;

                return ( C * serviceFeeCoefficient[entrust] ).toFixed(2)
            },
            handleTabSelect (state) {
                this.searchForm.state = state;
                this.getList();
            },
            showDetail (idx) {
                this.pointTask = {};
                this.pointIdx  = idx;
                this.getComments(this.pointTask.id)
            },
            getUpStrem () {
                let postData   = {};
                postData.p     = 1;
                postData.s     = 50;
                postData.state = 1;

                this.get('/api/v1/upstreams', postData, {loading: 'commentLoading', err: '获取匹配情报失败'})
                    .then(res => {
                        if (res.success) {
                            if (res.success && res.data.rows) {
                                this.upstreams = res.data.rows.map(e => {
                                    return {
                                        label: e.company_name,
                                        value: e.id
                                    }
                                });
                                this.upstreams.unshift({
                                    label: '',
                                    value: ''
                                })
                            }

                        } else {
                            this.upstreams = []
                        }
                    })
            },
            search () {
                this.getList()
            },
            getComments (taskId) {
                let postData  = {};
                postData.task = taskId;
                postData.p    = 1;
                postData.s    = 50;

                this.get('/api/v1/traces', postData, {loading: 'commentLoading', err: '获取匹配情报失败'})
                    .then(res => {
                        if (res.success && res.data.rows) {
                            this.storeComments = res.data.rows.map((e, i) => {
                                let ele  = e;
                                ele.bg   = `b${~~(Math.random() * 19 + 1)}`;
                                ele.type = this.commentMap[e.state] || '不明类型';
                                ele.time = e.last_update_at.split(' ')[0];
                                if (e.fingerprint) {
                                    ele.fingerprint = e.fingerprint;
                                    let lnglatXY    = ele.fingerprint.split(',').map(e => Number(e).toFixed(6));
                                    this.regeocoder(lnglatXY)
                                        .then(address => {
                                            this.storeComments[i].location = address;
                                        });
                                }
                                ele.location = e.state == 0 ? e.fingerprint || '不明' : e.location || '线人未描述';
                                return ele
                            })
                        } else {
                            this.storeComments = [];
                        }

                    })
            },
            adopt (commentId, name) {
                this.$confirm(`确定采纳【${name}】的情报为的最佳情报吗？该操作将会使任务进入已锁定状态`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.jax(`/api/v1/traces/${commentId}/confirm`, {}, {loading: 'xhrPending', errmsg: '采纳失败，请稍后再试'})
                        .then(res => {
                            if (res.success) {
                                this.msg('采纳成功');
                                this.getList();
                                this.getCount();
                            }
                        })
                }).catch(() => {
                    // do nothing
                });
            },
            effective (commentId, name) {
                this.$confirm(`确定将【${name}】的库存情报置为有效情报吗？该操作将会使任务进入下一阶段`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.jax(`/api/v1/traces/${commentId}/confirm`, {}, {loading: 'xhrPending', errmsg: '操作失败，请稍后再试'})
                        .then(res => {
                            if (res.success) {
                                this.msg('操作成功');
                                this.getList();
                                this.getCount();
                            }
                        })
                }).catch(() => {
                    // do nothing
                });
            },
            setTaskState () {
                let taskId = this.pointTask.id;

                this.$confirm(`确定将【${this.pointTask.car_number}】的任务${this.taskActionTxt}吗`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let postData = new FormData();
                    postData.append('state', this.taskNextState);

                    this.jax(`/api/v1/tasks/${taskId}/state`, postData, {errmsg: '采纳失败，请稍后再试'})
                        .then(res => {
                            if (res.success) {
                                this.msg('操作成功');
                                this.getList();
                                this.getCount();
                            }
                        })
                }).catch(() => {
                    // do nothing
                });

            },
            regeocoder (lnglatXY) {
                let self = this;
                return new Promise((resolve, reject) => {
                    this.geocoder.getAddress(lnglatXY, (status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            resolve(self.geocoder_CallBack(result))
                        } else {
                            console.log('获取地理位置失败');
                        }
                    });
                })
            },
            geocoder_CallBack(data) {
                return data.regeocode.formattedAddress; //返回地址描述
            },
            delTask (taskId) {
                this.$confirm(`确定将【${this.pointTask.car_number}】的任务删除吗`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let postData = new FormData();

                    this.jax(`/api/v1/tasks/${taskId}`, postData, {errmsg: '删除失败，请稍后再试', method: 'DELETE'})
                        .then(res => {
                            if (res.success) {
                                this.msg('操作成功');
                                this.getList();
                                this.getCount();
                            }
                        })
                }).catch(() => {
                    // do nothing
                });
            },
            getCount () {
                this.get('/api/v1/tasks/count?state=4').then(res => {
                    if (res.success) {
                        this.tasksCount4 = res.data.count
                    }
                });
                this.get('/api/v1/tasks/count?state=8').then(res => {
                    if (res.success) {
                        this.tasksCount8 = res.data.count
                    }
                });
                this.get('/api/v1/tasks/count?state=7').then(res => {
                    if (res.success) {
                        this.tasksCount7 = res.data.count
                    }
                });
            },
            sortIt () {
                if (this.sortWay) {
                    this.sortWay = !this.sortWay;
                    this.tasks   = this.tasks.sort((a, b) => {
                        return Number(b.car_price) - Number(a.car_price)
                    })
                } else {
                    this.sortWay = !this.sortWay;
                    this.getList()
                }

            }
        },
        components: {
            imgView
        }

    };
</script>

<template>
    <div class="tasks">
        <el-menu default-active="3" mode="horizontal" @select="handleTabSelect" layout="row center-left">
            <el-menu-item index="3">
                查找中
            </el-menu-item>
            <el-menu-item index="4">
                <el-badge :value="tasksCount4" :hidden="tasksCount4 == 0">已发现</el-badge>
            </el-menu-item>
            <el-menu-item index="8">
                <el-badge :value="tasksCount8" :hidden="tasksCount8 == 0">已锁定</el-badge>
            </el-menu-item>
            <el-menu-item index="7">
                <el-badge :value="tasksCount7" :hidden="tasksCount7 == 0">可清收</el-badge>
            </el-menu-item>
            <el-menu-item index="5,6">已完成</el-menu-item>
            <el-menu-item index="3,4,5,6,7,8">所有</el-menu-item>
            <div self="right" class="cb__bar-right" layout="row center-justify">
                <el-select v-model="searchForm.upstream" @change="search" filterable placeholder="按债权人搜索">
                    <el-option
                            v-for="item in upstreams"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
                <el-input
                        class="tasks__tool-input"
                        icon="search"
                        placeholder="按车牌搜索"
                        @change="search"
                        v-model="searchForm.c_num">
                </el-input>
            </div>
        </el-menu>
        <div class="tasks__content" layout="row top-left" v-loading.body="xhrPending">
            <div class="tasks__list">
                <div v-if="hasTask" class="task" :class="{'active': pointIdx == index}" v-for="(task, index) in tasks"
                     @click="showDetail(index)">
                    <span class="task__status" :class="task.stBg"></span>
                    <p class="task__car ac">
                        {{task.car_number}}{{task.extText}}
                    </p>
                    <p class="task__carid ac">{{task.car_color}} / {{task.car_type}}</p>
                    <p class="task__debtor ac">{{task.company_name}} / {{task.contact_phone}}</p>
                    <p class="task__time ac">{{task.time}}</p>
                    <p class="task__del ac" v-if="task.state == 6" @click.stop="delTask(task.id)">X</p>
                </div>
                <h3 class="tasks__empty" v-if="!hasTask">
                    暂无任务
                </h3>
            </div>
            <div class="tasks__detail" v-if="hasTask">
                <div class="detail__tool" layout="row center-right">
                    <h5 class="detail__title--big" self="left">
                        <p class="detail__title-main" layout="row center-left">
                            <span>{{pointTask.car_number}}{{pointTask.extText}}</span>
                        </p>
                        <p class="detail__title-sub">{{pointTask.car_type}}</p>
                    </h5>

                    <span class="detail__status" :class="pointTask.stBg"></span>
                    <span class="detail__status-word">{{pointTask.stMsg}}</span>
                    <el-button
                            type="'success'"
                            style="margin-left: 30px;"
                            v-if="pointTask.state == '7'"
                            @click="setTaskState"
                    >{{taskActionTxt}}
                    </el-button>
                </div>
                <div v-if="pointTask.entrust == '2'" class="trace__title">委托请收任务无情报选项</div>
                <div v-else class="trace__title">INTELLIGENCE</div>
                <!--<div class="detail__comments" layout="column top-left" >-->
                <div class="wh-table"
                     layout="column top-center"
                     v-loading.body="commentLoading"
                     style="margin: 20px 0;"
                     v-if="pointTask.entrust != '2'"
                >
                    <div class="wh-table__thead" layout="row center-left">
                        <div class="th w23">时间</div>
                        <div class="th w33">GPS地点</div>
                        <div class="th w10">线人</div>
                        <div class="th w14 tac">情报类型</div>
                        <div class="th w20 tac"><i class="el-icon-more"></i></div>
                    </div>
                    <div v-if="isCommentsEmpty" class="wh-table__tbody--empty">暂无关联情报</div>
                    <div v-else
                         class="wh-table__tbody slim"
                         layout="row center-left"
                         v-for="(comment, index) in storeComments"
                    >
                        <div class="td w23">
                            <el-tooltip placement="top" :content="comment.last_update_at">
                                {{comment.time}}
                            </el-tooltip>
                        </div>
                        <div class="td w33">{{comment.location}}</div>
                        <div class="td w10">{{comment.name}}</div>
                        <div class="td w14 tac">{{comment.type}}</div>
                        <div class="td w20 tac">
                            <el-button
                                    size="small"
                                    v-if="pointTask.state == '3' && comment.state == '0'"
                                    type="primary"
                                    @click="effective(comment.id, comment.name)"
                            >有效库存
                            </el-button>
                            <el-button
                                    size="small"
                                    v-if="pointTask.state == '4' && comment.state != '0'"
                                    type="primary"
                                    @click="adopt(comment.id, comment.name)"
                            >采纳
                            </el-button>
                            <div v-if="comment.is_result" layout="row center-center" class="best">
                                <i class="iconfont">&#xe70c;</i> <span>最佳情报</span>
                            </div>
                        </div>
                    </div>
                </div>
                <!--</div>-->
                <div class="detail__content" layout="row top-left">
                    <div class="detail__gap"></div>
                    <div class="detail__unit">
                        <h5 class="detail__title">车辆残值</h5>
                        <p class="detail__word">{{pointTask.car_price}} 万元</p>
                    </div>
                    <div class="detail__unit">
                        <h5 class="detail__title">{{entrustFeeMap[pointTask.entrust]}}费用</h5>
                        <p class="detail__word">{{pointTask.C}} 万元</p>
                    </div>
                    <div class="detail__unit">
                        <h5 class="detail__title">车辆颜色</h5>
                        <p class="detail__word">{{pointTask.car_color}}</p>
                    </div>
                    <div class="detail__unit">
                        <h5 class="detail__title">车辆识别号</h5>
                        <p class="detail__word">{{pointTask.car_id}}</p>
                    </div>
                    <div class="detail__unit">
                        <h5 class="detail__title">发动机号</h5>
                        <p class="detail__word">{{pointTask.engine_id}}</p>
                    </div>
                    <!-- 分割-->
                    <div class="detail__gap"></div>

                    <div v-if="pointTask.borrower" class="detail__stage1" layout="row top-left">
                        <div class="detail__unit">
                            <h5 class="detail__title">债权人</h5>
                            <p class="detail__word">{{pointTask.company_name}}</p>
                        </div>
                        <div class="detail__unit">
                            <h5 class="detail__title">债务人</h5>
                            <p class="detail__word">{{pointTask.debtor}}</p>
                        </div>
                        <div class="detail__unit">
                            <h5 class="detail__title">债务人身份证号</h5>
                            <p class="detail__word">{{pointTask.debtor_id_number}}</p>
                        </div>
                        <div class="detail__unit">
                            <h5 class="detail__title">债务人电话</h5>
                            <p class="detail__word">{{pointTask.debtor_phone}}</p>
                        </div>

                        <!-- 分割-->
                        <div class="detail__gap"></div>
                        <div class="detail__unit">
                            <h5 class="detail__title">贷款行</h5>
                            <p class="detail__word">{{pointTask.borrower}}</p>
                        </div>
                        <div class="detail__unit">
                            <h5 class="detail__title">贷款金额</h5>
                            <p class="detail__word">{{pointTask.loan_amount}}</p>
                        </div>
                        <div class="detail__unit">
                            <h5 class="detail__title">贷款余额</h5>
                            <p class="detail__word">{{pointTask.loan_rest}}</p>
                        </div>

                        <!-- 分割-->
                        <div class="detail__gap"></div>

                        <div class="detail__unit--img">
                            <h5 class="detail__title">代偿证明</h5>
                            <imgView :src="pointTask.compensatory"></imgView>
                        </div>
                        <div class="detail__unit--img">
                            <h5 class="detail__title">法院判决书</h5>
                            <imgView :src="pointTask.court_decision"></imgView>
                        </div>

                        <!-- 分割-->
                        <div class="detail__gap detail__gap--t"></div>

                        <div class="detail__unit--img">
                            <h5 class="detail__title">贷款行合同</h5>
                            <imgView :src="pointTask.loan_contract"></imgView>
                        </div>
                        <div class="detail__unit--img">
                            <h5 class="detail__title">担保单位协议书</h5>
                            <imgView :src="pointTask.guarantor_contract"></imgView>
                        </div>
                        <div class="detail__unit--img">
                            <h5 class="detail__title">机动车登记证书（一）</h5>
                            <imgView :src="pointTask.car_register1"></imgView>
                        </div>
                        <div class="detail__unit--img">
                            <h5 class="detail__title">机动车登记证书（二）</h5>
                            <imgView :src="pointTask.car_register2"></imgView>
                        </div>
                        <div class="detail__unit--img">
                            <h5 class="detail__title">债务人身份证照片</h5>
                            <imgView :src="pointTask.debtor_id"></imgView>
                        </div>
                        <div class="detail__unit--img">
                            <h5 class="detail__title">委托书</h5>
                            <imgView :src="pointTask.delegation"></imgView>
                        </div>
                    </div>
                    <div v-else layout="row top-left" class="detail__stage2 ">
                        任务正处于第一阶段
                    </div>
                </div>
            </div>
        </div>
        <div class="tasks__download-bth tasks__download-bth--sort"
             :class="sortWay ? 'tasks__download-bth--success' : ''" layout="row center-center" @click="sortIt">
            <i class="iconfont ">&#xe804;</i>
        </div>
        <a download :href="downloadHref" class="tasks__download-bth" layout="row center-center">
            <i class="iconfont ">&#xe63b;</i>
        </a>
    </div>
</template>